
const path = require('path')
const dotenv = require('dotenv')
dotenv.config({
    path: path.resolve('./', '.env')
})
const dayjs = require('dayjs');
const { sendEmail } = require('./utils.js')
const fs = require('fs')

const { promisePool } = require('./mysql.js')
const isBetween = require('dayjs/plugin/isBetween')
const relativeTime = require('dayjs/plugin/relativeTime')

dayjs.extend(isBetween)
dayjs.extend(relativeTime)

// const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIzIiwianRpIjoiYzc3MjgyY2QzMmRkZmIxMWNjYTljMTIyN2FiZjE3NzFlNjA3NzVlYmRiODYzY2YxZWNhNzkyMjNkMGMxZTI2MWZjMGZhMDhlYmIyYTM0MDkiLCJpYXQiOjE3NDk1MzYyMzUsIm5iZiI6MTc0OTUzNjIzNSwiZXhwIjoxNzY1MDg4MjM1LCJzdWIiOiIxNzIwOTg1Iiwic2NvcGVzIjpbXX0.gjf3r5bI0TU75YvaazOah9jvwQAWgAGNri-H4KUEVzNxtktiyw0KEVH8uionbXkmGzEKNx6lf43DiGZcNgpj-7TRw5aOfhMBdbfgmu2WWiASIWD278pzbP19x1VzclcQRTPF3PKCkUldFAMFVyMtjKW9AAbw--HHrvMPwLPbRDWRNZu_QuH-LNjkI6ptvvmbie-AOJRSO9yRbHPV4VIV8DRj0JAtAcY2Dk5IxP7yNDeWUiZhhRB8VBORhnypZsAX7Q4mlLtnyQK_-AZwNfoDuEi725eaSzpxWyCG3hrHI4AOfcHmU2w32ct5t02er3hcN6TDXJ1xVwtg80vZNYYizFn_v_Ds4YskXxjlqx8FkemZtgnVsoBvfSFKbfruloaaK-FyCsL-y2aabei_kRgC-vdtgbTY_bfs41vG6dFFJOxvrsirDA7ZTSINZiJv07wlOp18QusJvGTnCaA00E0qMc10Z9BiPQUXByH4UVFujFRgTifYrnQclFV9yyHKDsLQ9-i-dtx989xhodwgIMfJLhX2zTdtRSWcONN45TK5PbHr3pvNUviYEr4hGmk_4CZnfXiEWW0psqChGTgZ8dT8JQZ4jHP1DWkQ6o9BRSIv1PIsvnwaDR-Xdt837MJcZLnAcspmKbk82EZWBpjMKbfhk1k6iGYtB5bbX1P7IJiyYL0'
const checkLink = async () => {
    try {
        const [resu] = await promisePool.execute('SELECT * FROM `times` where id=1')
        let result = {}
        if (!resu || resu.length !== 1) {
            return
        } else {
            result = resu[0]
        }

        const filePath = path.resolve('../', 'time.txt')
        // 设定开始和结束时间
        const startTime = dayjs().startOf('day').add(6, 'hour'); // 设置开始时间为当天的6点
        const endTime = dayjs().startOf('day').add(22, 'hour'); // 设置结束时间为当天的22点
        let timeStemp = 3
        timeStemp = timeStemp + Math.random().toFixed(1) * 10
        timeStemp = timeStemp * 1000 * 60
        // const jsonConfig = await fs.readFileSync(process.env.JSON_LOCATION, 'utf-8')
        // const temp = JSON.parse(jsonConfig)
        const { time, days, email, doctorId, token } = result
        const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
        time.forEach(it => {
            const targetTime = dayjs().hour(it).minute(0).second(0).millisecond(0)
            const diff = targetTime.diff(now, 'milliseconds');
            if (diff < timeStemp && diff > 0) {
                timeStemp = diff + 2000
            }
        })

        // 获取当前时间

        // console.log(startTime.format("YYYY-MM-DD HH:mm:ss"));
        fs.appendFileSync(filePath, now + '\n')
        // console.log(filePath, '写入时间');

        // 判断当前时间是否在这个时间范围内
        const isInTimeRange = dayjs(now).isBetween(startTime, endTime);
        if (isInTimeRange) {

            const result = await fetch('https://wxmini.xyhospital.com/api/patient/number/getDoctorDetail', {
                cache: 'no-store',
                // next: { revalidate: 0 },
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Accept': 'application/prs.xyhospital.v1+json',
                    "content-type": "application/json"
                },
                method: 'POST',
                body: JSON.stringify({
                    deptCode: "%",
                    // "doctorCode": "51946", // 闫明轩
                    // "doctorCode": "51047", // 王小媛
                    "doctorCode": doctorId

                })
            })
            if (result.ok) {
                try {
                    const data = await result.json();

                    const list = data.data.data
                    // console.log(list);
                    const li = list.filter(it => it.Remain != '0' && days.includes(it.day))
                    if (li.length > 0) {
                        const str = li.map(it => it.day).join(',')
                        email.forEach(it => {
                            sendEmail(`可以预约${str}号了`, it)
                        })

                    }
                } catch (error) {
                    sendEmail('服务失败了')
                    fs.appendFileSync(filePath, error.toString() + '\n')
                }
            } else if (result.status === 401) {
                sendEmail('token失效了')
                return
            }
        }

        setTimeout(async () => {
            checkLink()
        }, timeStemp)
    } catch (error) {
        console.error('Error loading environment variables:', error);
    }



}

checkLink()